<!--- 客户详情页面（根据原型仅保留：基本信息、设备信息、合同信息） --->
<script setup lang="ts">
  import { ref, computed, watch } from 'vue';
  import { Message } from '@arco-design/web-vue';
  import { useSkeleton } from '@/hooks/arco/useSkeleton';
  import SkeletonView from '@/components/skeleton-view/index.vue';
  import * as Lodash from 'lodash';
  import dayjs from 'dayjs';
  import { getElderDetail } from '@/api/customerManagement/profile';
  import { queryElderDeviceSummary } from '@/api/customerManagement/device';
  import {
    queryElderContractList,
    queryElderContractDetail,
    createElderContract,
    deleteElderContract,
    genContractFileUploadToken,
  } from '@/api/customerManagement/contract';
  import { useForm } from '@/hooks/arco/useForm';
  import { useUploader } from '@/hooks/useUploader';
  import { showWarningConfirm } from '@/hooks/arco/showWarningConfirm';
  import type { RequestOption } from '@arco-design/web-vue';
  

  const emits = defineEmits(['update', 'edit', 'openDevice']);
  const props = defineProps({
    elderId: {
      type: String,
      default: '',
    },
    activeTabKey: {
      type: String,
      default: 'base-info',
    },
  });

  // 选项卡
  const tabActiveKey = ref<'base-info' | 'device-info' | 'contract-info'>(
    props.activeTabKey as any
  );

  // 家属关系映射表
  const familyRelationMap: Record<string, string> = {
    '11': '配偶',
    '12': '儿子',
    '13': '女儿',
    '14': '儿媳',
    '15': '女婿',
    '16': '兄弟',
    '17': '姐们',
    '18': '孙子/孙女',
    '99': '其他',
  };

  // 基本信息字段映射（根据后端返回字段，缺失则展示—）
  const baseInfoKeyMap: Record<string, string> = {
    elderId: '客户ID',
    elderName: '客户姓名',
    idCardTypeName: '证件类型',
    idCardNo: '证件号码',
    genderName: '性别',
    birthdate: '出生日期',
    phone: '联系电话',
    regionName: '所在地区',
    address: '详细地址',
    contractStatusName: '签约状态',
    stationName: '关联站点',
    familyName: '家属姓名',
    familyRelationName: '家属关系',
    familyPhone: '家属电话',
  };

  const elderId = ref(props.elderId);
  const currentItem = ref<Record<string, any>>({});


  // 点击编辑：将当前客户数据抛给父组件，由父组件打开编辑弹窗
  const handleEditClick = () => {
    try {
      const data = Lodash.cloneDeep(currentItem.value || {});
      emits('edit', data);
    } catch (e) {
      emits('edit', currentItem.value || {});
    }
  };

  // 基本信息
  const baseInfoComputed = computed(() => {
    const outputs: any[] = [];
    Lodash.keys(baseInfoKeyMap).forEach((key) => {
      let value = currentItem.value?.[key];
      if (key === 'genderName') {
        const g = currentItem.value?.gender;
        if (g === 1) {
          value = '男';
        } else if (g === 2) {
          value = '女';
        } else {
          value = '—';
        }
      }
      // 所在地区：优先使用后端 regionName；缺失时按 省/市/区名称拼接
      if (key === 'regionName') {
        const region = currentItem.value?.regionName;
        if (!region) {
          const p = currentItem.value?.provinceName || '';
          const c = currentItem.value?.cityName || '';
          const d = currentItem.value?.districtName || '';
          const joined = `${p}${c}${d}`.trim();
          value = joined || '—';
        } else {
          value = region;
        }
      }
      // createdAt / updatedAt 统一格式化（支持数组或字符串）
      if (key === 'createdAt' || key === 'updatedAt') {
        const v = currentItem.value?.[key];
        if (Array.isArray(v) && v.length >= 3) {
          const [y, m, d, hh = 0, mm = 0, ss = 0] = v;
          value = dayjs(new Date(y, m - 1, d, hh, mm, ss)).format(
            'YYYY-MM-DD HH:mm:ss'
          );
        } else if (v) {
          const dv = dayjs(v);
          value = dv.isValid() ? dv.format('YYYY-MM-DD HH:mm:ss') : String(v);
        }
      }
      // 家属关系：优先显示 familyRelationName；如果返回的是 code，则进行映射转换
      if (key === 'familyRelationName') {
        const code = currentItem.value?.familyRelation;
        if (code) {
          value = familyRelationMap[String(code)] || code;
        } else if (currentItem.value?.familyRelationName) {
          value = currentItem.value.familyRelationName;
        } else {
          value = '—';
        }
      }
      if (!value && value !== 0) {
        value = '—';
      }
      outputs.push({
        key,
        value,
        label: baseInfoKeyMap[key],
      });
    });
    return outputs;
  });

  // 设备汇总卡片视图
  const deviceSummaryLoading = ref(false);
  const deviceSummaryGroups = ref<Array<{ name: string; items: any[] }>>([]);

  // 合同：列表、查看、新增
  const contracts = ref<any[]>([]);
  const contractsLoading = ref(false);

  // 定义函数 - 在watch之前定义，避免函数未初始化错误
  const loadDeviceSummary = () => {
    deviceSummaryLoading.value = true;
    return queryElderDeviceSummary({ elderId: elderId.value })
      .then((res) => {
        deviceSummaryGroups.value = transformDeviceSummary(res);
      })
      .finally(() => {
        deviceSummaryLoading.value = false;
      });
  };

  const loadContracts = () => {
    contractsLoading.value = true;
    return queryElderContractList({
      pageNum: 1,
      pageSize: 100,
      elderId: elderId.value,
    })
      .then((res) => {
        // 后端可能返回 { list, total } 或直接数组，这里做兼容
        const list = Array.isArray(res?.list) ? res.list : res;
        contracts.value = list || [];
      })
      .finally(() => {
        contractsLoading.value = false;
      });
  };

  // 获取详情
  const itemData = useSkeleton<any, any[]>({
    apiFun: getElderDetail,
    initQueryParams: [elderId.value],
    onSuccess(data) {
      if (data) {
        currentItem.value = data;
      }
    },
  });

  // 监听update事件，刷新详情数据
  watch(
    () => props.elderId,
    (newVal) => {
      console.log('detail.vue接收到elderId:', newVal);
      if (newVal) {
        elderId.value = newVal;
        itemData.execute(elderId.value);
        // 刷新设备汇总与合同列表
        loadDeviceSummary();
        loadContracts();
      }
    },
    { immediate: true }
  );

  watch(
    () => props.activeTabKey,
    (key) => {
      if (key) tabActiveKey.value = key as any;
    },
    { immediate: true }
  );

  // 监听update事件，确保数据及时刷新
  const handleUpdate = () => {
    if (elderId.value) {
      itemData.execute(elderId.value);
      loadDeviceSummary();
      loadContracts();
    }
  };

  // 将handleUpdate方法暴露给父组件
  defineExpose({ handleUpdate });

  function getModelIdFromRaw(raw: any) {
    return (
      raw?.deviceModelId || raw?.modelId || raw?.deviceTypeId || raw?.id || ''
    );
  }

  function handleDeviceDetail(item: any) {
    const mid = getModelIdFromRaw(item?.raw || {});
    if (!mid || !item?.count) return;
    emits('openDevice', {
      elderId: elderId.value,
      modelId: mid,
      modelName: item?.name || '',
    });
  }

  function getCategoryName(e: any) {
    return (
      e?.deviceGroupName ||
      e?.categoryName ||
      e?.groupName ||
      e?.typeCategory ||
      e?.deviceCategory ||
      '其他设备类'
    );
  }

  function getDeviceName(e: any) {
    return (
      e?.deviceModelName ||
      e?.deviceName ||
      e?.deviceTypeName ||
      e?.name ||
      e?.title ||
      '设备'
    );
  }

  function getInstallCount(e: any) {
    const n =
      e?.installCount ??
      e?.installNumber ??
      e?.installNum ??
      e?.count ??
      e?.total ??
      0;
    const v = Number(n);
    return Number.isNaN(v) ? 0 : v;
  }

  function getFeeText(e: any) {
    const arr =
      e?.paymentTypeNames ||
      e?.feeTypeNames ||
      e?.payTypeNames ||
      e?.feeTypes ||
      e?.payTypes;
    if (Array.isArray(arr)) return arr.filter(Boolean).join('；');
    return e?.feeTypeName || e?.payTypeName || e?.feeType || e?.payType || '—';
  }

  const transformDeviceSummary = (res: any) => {
    // 1) 适配 docs/api/客户设备返回的数据.json 的结构：{ code, msg, data: [ { deviceGroupName, deviceList: [...] } ] }
    if (Array.isArray(res?.data)) {
      const groups: Array<{ name: string; items: any[] }> = res.data.map(
        (g: any) => {
          const name = g?.deviceGroupName || g?.groupName || '其他设备类';
          const items = (Array.isArray(g?.deviceList) ? g.deviceList : []).map(
            (e: any) => {
              const count = getInstallCount(e);
              const installed =
                typeof e?.installStatus !== 'undefined'
                  ? String(e.installStatus) !== '0'
                  : count > 0 ||
                    (e?.installStatusLabel &&
                      !String(e.installStatusLabel).includes('未'));
              const feeText = Array.isArray(e?.paymentTypeNames)
                ? e.paymentTypeNames.filter(Boolean).join('；')
                : getFeeText(e);
              return {
                icon: e?.deviceModelIcon || '',
                name: getDeviceName(e),
                installed,
                count,
                feeText,
                raw: e,
              };
            }
          );
          return { name, items };
        }
      );
      const order = ['紧急求救类', '环境监测类', '跌倒检测类', '体征监测类'];
      groups.sort((a, b) => {
        const ia = order.indexOf(a.name);
        const ib = order.indexOf(b.name);
        if (ia === -1 && ib === -1) return a.name.localeCompare(b.name);
        if (ia === -1) return 1;
        if (ib === -1) return -1;
        return ia - ib;
      });
      return groups;
    }

    // 1.1) 适配 sendRequest 已将 data 直接作为返回值的情况：res 即为 [{ deviceGroupName, deviceList }]
    if (
      Array.isArray(res) &&
      res.length > 0 &&
      (res[0]?.deviceGroupName || res[0]?.groupName) &&
      Array.isArray(res[0]?.deviceList)
    ) {
      const groups: Array<{ name: string; items: any[] }> = (res as any[]).map(
        (g: any) => {
          const name = g?.deviceGroupName || g?.groupName || '其他设备类';
          const items = (Array.isArray(g?.deviceList) ? g.deviceList : []).map(
            (e: any) => {
              const count = getInstallCount(e);
              const installed =
                typeof e?.installStatus !== 'undefined'
                  ? String(e.installStatus) !== '0'
                  : count > 0 ||
                    (e?.installStatusLabel &&
                      !String(e.installStatusLabel).includes('未'));
              const feeText = Array.isArray(e?.paymentTypeNames)
                ? e.paymentTypeNames.filter(Boolean).join('；')
                : getFeeText(e);
              return {
                icon: e?.deviceModelIcon || '',
                name: getDeviceName(e),
                installed,
                count,
                feeText,
                raw: e,
              };
            }
          );
          return { name, items };
        }
      );
      const order = ['紧急求救类', '环境监测类', '跌倒检测类', '体征监测类'];
      groups.sort((a, b) => {
        const ia = order.indexOf(a.name);
        const ib = order.indexOf(b.name);
        if (ia === -1 && ib === -1) return a.name.localeCompare(b.name);
        if (ia === -1) return 1;
        if (ib === -1) return -1;
        return ia - ib;
      });
      return groups;
    }

    // 2) 兼容其他可能的结构：res.groups / res.list / 直接数组
    const list: any[] = Array.isArray(res?.groups)
      ? res.groups.flatMap((g: any) => g.items || g.deviceList || [])
      : Array.isArray(res)
      ? res
      : res?.list || res?.data || [];

    const map = new Map<string, any[]>();
    list.forEach((e) => {
      const cat = getCategoryName(e);
      if (!map.has(cat)) map.set(cat, []);
      const count = getInstallCount(e);
      const installed =
        typeof e?.installStatus !== 'undefined'
          ? String(e.installStatus) !== '0'
          : count > 0;
      map.get(cat)!.push({
        icon: e?.deviceModelIcon || '',
        name: getDeviceName(e),
        installed,
        count,
        feeText: getFeeText(e),
        raw: e,
      });
    });

    const groups: Array<{ name: string; items: any[] }> = [];
    map.forEach((items, name) => groups.push({ name, items }));
    const order = ['紧急求救类', '环境监测类', '跌倒检测类', '体征监测类'];
    groups.sort((a, b) => {
      const ia = order.indexOf(a.name);
      const ib = order.indexOf(b.name);
      if (ia === -1 && ib === -1) return a.name.localeCompare(b.name);
      if (ia === -1) return 1;
      if (ib === -1) return -1;
      return ia - ib;
    });
    return groups;
  };

  const fmtDate = (d: any) => {
    if (!d) return '—';
    return dayjs(d).format('YYYY-MM-DD');
  };

  const isActive = (item: any) => {
    // 优先使用后端状态字段；没有则通过日期判断
    if (item?.statusName) {
      return item.statusName.includes('有效');
    }
    if (item?.status) {
      return String(item.status) === '1';
    }
    if (item?.expiryDate) {
      return dayjs(item.expiryDate).isAfter(dayjs());
    }
    return false;
  };

  // 新增合同弹窗
  const addVisible = ref(false);
  const addForm = useForm({
    state: {
      title: '',
      effectiveDate: '',
      expiryDate: '',
    },
    rules: {
      title: { required: true, message: '请输入合同标题' },
      effectiveDate: { required: true, message: '请选择生效时间' },
      expiryDate: { required: true, message: '请选择失效时间' },
    },
  });
  const fileUploader = useUploader({
    apiFun: genContractFileUploadToken,
    props: {
      listType: 'text',
      defaultFileList: [],
      limit: 1,
      onBeforeUpload(file: any) {
        const isPdf =
          file?.type === 'application/pdf' || /\.pdf$/i.test(file?.name || '');
        if (!isPdf) {
          Message.error('仅支持上传 PDF 文件');
          return false;
        }
        return true;
      },
    },
  });

  // 记录上传的文件名（仅一个文件，可为空）
  const uploadedFileName = ref<string>('');

  // 自定义上传方法（返回包含 abort 的对象，满足类型 UploadRequest 的结构要求）
  const uploadCustomRequest = (option: RequestOption) => {
    fileUploader.handleUpload(option);
    return {
      abort() {
        // 目前不暴露取消上传能力，提供空实现以满足类型结构
      },
    } as any;
  };

  // 上传变更时同步文件名
  const onUploadChange = (fileList: any, file: any) => {
    try {
      // 同步内部上传结果（用于 getResourceIds 获取资源ID）
      fileUploader.handleChange(fileList);
      // 优先从本次变更的文件项获取文件名
      if (file && file.status === 'done') {
        uploadedFileName.value = file?.name || file?.file?.name || '';
      }
      // 兜底：从文件列表中最后一个已完成项获取文件名或服务端返回的 key
      if (!uploadedFileName.value) {
        const list = Array.isArray(fileList) ? fileList : [];
        const lastDone = list.filter((i: any) => i?.status === 'done').pop();
        uploadedFileName.value =
          lastDone?.name ||
          lastDone?.file?.name ||
          lastDone?.response?.key ||
          '';
      }
    } catch (e) {
      // 忽略异常，避免影响保存逻辑
    }
  };

  // 删除已选文件时，清空文件名记录
  const onBeforeRemove = (file: any) => {
    const ok = fileUploader.handleBeforeRemove(file);
    uploadedFileName.value = '';
    return ok;
  };

  // 统一在组件层做一次 PDF 类型校验（与 useUploader.props.onBeforeUpload 保持一致）
  const pdfBeforeUpload = (file: any) => {
    const isPdf =
      file?.type === 'application/pdf' || /\.pdf$/i.test(file?.name || '');
    if (!isPdf) {
      Message.error('仅支持上传 PDF 文件');
      return false;
    }
    return true;
  };

  const openAdd = () => {
    addForm.backToInit();
    fileUploader.props.defaultFileList = [];
    uploadedFileName.value = '';
    addVisible.value = true;
  };

  const saveAdd = async () => {
    await addForm.validate();
    const payload: any = {
      elderId: elderId.value,
      title: addForm.state.title,
      effectiveDate: addForm.state.effectiveDate
        ? dayjs(addForm.state.effectiveDate).format('YYYY-MM-DD')
        : '',
      expiryDate: addForm.state.expiryDate
        ? dayjs(addForm.state.expiryDate).format('YYYY-MM-DD')
        : '',
    };
    const resIds = fileUploader.getResourceIds();
    console.log('上传的文件ID:', resIds);
    if (
      Array.isArray(resIds) &&
      resIds.length > 0 &&
      resIds[0] !== undefined &&
      resIds[0] !== null
    ) {
      payload.qiniuResId = resIds[0];
    }
    if (uploadedFileName.value) {
      payload.contractFileName = uploadedFileName.value;
    }
    return createElderContract(payload)
      .then(() => {
        Message.success('创建成功！');
        addVisible.value = false;
        loadContracts();
      })
      .catch(() => {})
      .finally(() => {});
  };

  // 查看合同
  const viewVisible = ref(false);
  const viewItem = ref<any>({});
  const onView = (row: any) => {
    viewVisible.value = true;
    viewItem.value = row;
    queryElderContractDetail(row.contractId)
      .then((res) => {
        viewItem.value = { ...row, ...res };
      })
      .catch(() => {});
  };

  // 删除合同
  const onDelete = (row: any) => {
    showWarningConfirm({
      title: '是否确定删除此合同吗?',
      content: '删除后不可恢复',
      onBeforeOk: () => deleteElderContract(row.contractId),
      onSuccess: () => {
        Message.success('删除成功');
        loadContracts();
      },
    });
  };

  const handleTabChange = (key: string | number) => {
    // Arco Tabs 的切换回调支持 string | number，这里统一处理为 string
    tabActiveKey.value = String(key) as any;
  };

  watch(
    () => props.elderId,
    (newVal) => {
      console.log('detail.vue接收到elderId:', newVal);
      if (newVal) {
        elderId.value = newVal;
        itemData.execute(elderId.value);
        // 刷新设备汇总与合同列表
        loadDeviceSummary();
        loadContracts();
      }
    },
    { immediate: true }
  );
</script>

<template>
  <div class="m-employee-info flex-col">
    <div class="me-info-body">
      <skeleton-view v-bind="itemData.bindProps">
        <a-tabs v-model:active-key="tabActiveKey" @change="handleTabChange">
          <!-- 基本信息 -->
          <a-tab-pane key="base-info" title="基本信息">
            <div class="info-container">
              <ul class="me-info-body-items">
                <li
                  v-for="(item, index) of baseInfoComputed"
                  :key="'info-' + index"
                >
                  <span class="label">{{ item.label }}</span>
                  <span class="value">{{ item.value }}</span>
                </li>
              </ul>
              <div class="me-info-actions">
                <a-button type="primary" size="small" @click="handleEditClick">
                  编辑
                </a-button>
              </div>
            </div>
          </a-tab-pane>

          <!-- 设备信息（汇总卡片视图） -->
          <a-tab-pane key="device-info" title="设备信息">
            <div class="device-summary">
              <a-spin :loading="deviceSummaryLoading">
                <template v-if="deviceSummaryGroups.length">
                  <div
                    v-for="group in deviceSummaryGroups"
                    :key="group.name"
                    class="ds-group"
                  >
                    <div class="ds-group-title">{{ group.name }}</div>
                    <div class="ds-cards">
                      <a-card
                        v-for="item in group.items"
                        :key="item.name + '-' + item.count"
                        class="ds-card"
                        :bordered="true"
                      >
                        <div class="ds-header">
                          <div class="ds-title">{{ item.name }}</div>
                          <a-tag
                            v-if="item.installed"
                            color="#00b42a"
                            size="small"
                            >已安装</a-tag
                          >
                          <a-tag v-else color="#f53f3f" size="small"
                            >未安装</a-tag
                          >
                        </div>
                        <div class="ds-body">
                          <img :src="item.icon" alt="" class="ds-icon" />
                          <div class="ds-info">
                            <div class="ds-row">
                              <span class="label">安装数量：</span>
                              <span class="value">{{ item.count }}台</span>
                            </div>
                            <!-- <div class="ds-row">
                              <span class="label">付费类型：</span>
                              <span class="value">{{ item.feeText || '—' }}</span>
                            </div> -->
                          </div>
                        </div>
                        <div class="ds-actions">
                          <a-button
                            type="primary"
                            size="small"
                            :disabled="!item.count"
                            @click="handleDeviceDetail(item)"
                            >设备详情</a-button
                          >
                        </div>
                      </a-card>
                    </div>
                  </div>
                </template>
                <a-empty v-else description="暂无设备信息" />
              </a-spin>
            </div>
          </a-tab-pane>

          <!-- 合同信息 -->
          <a-tab-pane key="contract-info" title="合同信息">
            <div class="contract-list">
              <a-spin :loading="contractsLoading">
                <div class="contract-cards">
                  <a-card
                    v-for="item in contracts"
                    :key="item.id"
                    class="contract-card"
                    :bordered="true"
                  >
                    <div class="cc-header">
                      <div class="cc-title">{{ item.title || '—' }}</div>
                      <a-tag v-if="isActive(item)" color="#00b42a" size="small"
                        >有效</a-tag
                      >
                      <a-tag v-else color="#ff7d00" size="small">失效</a-tag>
                    </div>
                    <div class="cc-body">
                      <div class="cc-row">
                        <span class="label">生效日期</span>
                        <span class="value">{{
                          fmtDate(item.effectiveDate)
                        }}</span>
                      </div>
                      <div class="cc-row">
                        <span class="label">失效日期</span>
                        <span class="value">{{
                          fmtDate(item.expiryDate)
                        }}</span>
                      </div>
                    </div>
                    <div class="cc-actions">
                      <a-space>
                        <a-button
                          size="small"
                          class="btn-delete"
                          type="secondary"
                          @click="onDelete(item)"
                          >删除</a-button
                        >
                        <a-button
                          size="small"
                          type="primary"
                          @click="onView(item)"
                          >查看</a-button
                        >
                      </a-space>
                    </div>
                  </a-card>

                  <!-- 新增卡片 -->
                  <a-card
                    class="contract-card add-card"
                    :bordered="true"
                    @click="openAdd"
                  >
                    <div class="add-inner">
                      <icon-plus />
                      <div class="add-text">点击上传合同</div>
                    </div>
                  </a-card>
                </div>
              </a-spin>
            </div>

            <!-- 新增合同弹窗 -->
            <a-modal
              v-model:visible="addVisible"
              title="新增合同"
              :mask-closable="false"
            >
              <a-form v-bind="addForm.bindProps" layout="vertical">
                <a-form-item field="title" label="合同标题" required>
                  <a-input
                    v-model="addForm.state.title"
                    placeholder="请输入合同标题"
                  />
                </a-form-item>
                <a-form-item field="effectiveDate" label="生效时间" required>
                  <a-date-picker
                    v-model="addForm.state.effectiveDate"
                    format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </a-form-item>
                <a-form-item field="expiryDate" label="失效时间" required>
                  <a-date-picker
                    v-model="addForm.state.expiryDate"
                    format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </a-form-item>
                <a-form-item label="合同文件（支持PDF格式）">
                  <a-upload
                    list-type="text"
                    :default-file-list="fileUploader.props.defaultFileList as any"
                    :custom-request="uploadCustomRequest"
                    :limit="1"
                    :accept="'.pdf'"
                    :before-upload="pdfBeforeUpload"
                    :before-remove="onBeforeRemove"
                    @change="onUploadChange"
                  >
                    <a-button type="primary"><icon-upload /> 点击上传</a-button>
                  </a-upload>
                </a-form-item>
              </a-form>
              <template #footer>
                <a-space>
                  <a-button @click="addVisible = false">取消</a-button>
                  <a-button type="primary" @click="saveAdd">保存</a-button>
                </a-space>
              </template>
            </a-modal>

            <!-- 查看合同弹窗 -->
            <a-modal
              v-model:visible="viewVisible"
              title="合同详情"
              :footer="false"
            >
              <div class="view-wrap">
                <div class="cc-row"
                  ><span class="label">合同标题：</span
                  ><span class="value">{{ viewItem.title || '—' }}</span></div
                >
                <div class="cc-row"
                  ><span class="label">生效日期：</span
                  ><span class="value">{{
                    fmtDate(viewItem.effectiveDate)
                  }}</span></div
                >
                <div class="cc-row"
                  ><span class="label">失效日期：</span
                  ><span class="value">{{
                    fmtDate(viewItem.expiryDate)
                  }}</span></div
                >
                <div class="cc-row"
                  ><span class="label">状态：</span
                  ><span class="value">{{
                    isActive(viewItem) ? '有效' : '失效'
                  }}</span></div
                >
                <div v-if="viewItem?.contractFileName" class="cc-row">
                  <span class="label">合同文件：</span>
                  <span class="value">
                    <a
                      v-if="viewItem.contractFileUrl"
                      :href="viewItem.contractFileUrl"
                      target="_blank"
                      style="color: blue; text-decoration: underline"
                      >{{ viewItem.contractFileName || '已上传文件' }}</a
                    >
                    <span v-else>{{
                      viewItem.contractFileName || '已上传文件'
                    }}</span>
                  </span>
                </div>
              </div>
            </a-modal>
          </a-tab-pane>
        </a-tabs>
      </skeleton-view>
    </div>
  </div>
</template>

<style lang="less" scoped>
  .m-employee-info {
    height: 100%;
  }
  .me-info-body {
    padding: 10px;
    flex: 1;
    position: relative;

    .me-info-body-items {
      display: grid;
      grid-template-columns: repeat(2, minmax(0, 1fr));
      column-gap: 60px;
      row-gap: 8px;
      padding: 0;

      & > li {
        margin-top: 8px;
        display: flex;
      }

      .label {
        display: inline-block;
        width: 90px;
        text-align: right;
        color: var(--color-text-1);
        margin-right: 20px;
      }

      .value {
        display: inline-block;
        color: var(--color-text-2);
        min-width: 60px;
        margin-right: 20px;
      }
    }

    .info-container {
      position: relative;
      width: 100%;
    }

    .me-info-actions {
      display: flex;
      justify-content: flex-end;
      margin-top: 20px;
      padding-right: calc((100% - 50%) / 2); /* 计算与第二列右对齐的内边距 */
    }

    .contract-list {
      padding: 10px 0;
    }
    .contract-cards {
      display: flex;
      flex-wrap: wrap;
      gap: 12px;
    }
    .contract-card {
      flex: 0 0 320px;
      width: 320px;
      min-height: 170px;
    }
    .cc-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: 600;
      margin-bottom: 8px;
    }
    .cc-title {
      color: var(--color-text-1);
    }
    .cc-body {
      color: var(--color-text-2);
      margin: 10px 0 14px;
    }
    .cc-row {
      display: flex;
      margin-top: 6px;
    }
    .cc-actions {
      display: flex;
      justify-content: flex-end;
    }
    .btn-delete {
      background: var(--color-fill-3);
      border-color: var(--color-fill-3);
      color: #fff;
    }
    .btn-delete:hover {
      background: var(--color-fill-4);
      border-color: var(--color-fill-4);
      color: #fff;
    }
    .cc-row .label {
      width: 90px;
      text-align: right;
      margin-right: 12px;
      color: var(--color-text-1);
    }
    .cc-row .value {
      flex: 1;
      color: var(--color-text-2);
    }
    .add-card {
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .add-inner {
      width: 100%;
      height: 120px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: var(--color-text-2);
    }
    .add-text {
      margin-top: 6px;
    }

    /* 设备汇总样式 */
    .device-summary {
      padding: 10px 0;
    }
    .ds-group {
      margin-bottom: 16px;
    }
    .ds-group-title {
      font-size: 16px;
      font-weight: 600;
      margin: 6px 4px 10px;
      color: var(--color-text-1);
    }
    /* 改为横向排列：使用 flex + 自动换行，每张卡片固定宽度 */
    .ds-cards {
      display: flex;
      flex-wrap: wrap;
      gap: 12px;
    }
    .ds-card {
      flex: 0 0 360px;
      max-width: 100%;
      min-height: 160px;
      position: relative;
    }
    @media (max-width: 1200px) {
      .ds-card {
        flex-basis: 320px;
      }
    }
    .ds-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: 600;
      margin-bottom: 8px;
    }
    .ds-title {
      color: var(--color-text-1);
    }
    .ds-body {
      color: var(--color-text-2);
      margin: 8px 0 10px;
      display: flex;
      align-items: flex-start; /* 顶部对齐 */
    }
    .ds-icon {
      width: 56px;
      height: 56px;
      margin-right: 12px;
      object-fit: contain;
      border-radius: 6px;
      background: var(--color-fill-2);
    }
    .ds-info {
      flex: 1;
      min-width: 0;
    }
    .ds-row {
      display: flex;
      margin-top: 6px;
    }
    .ds-row .label {
      width: 110px;
      text-align: right;
      margin-right: 12px;
      color: var(--color-text-1);
    }
    .ds-row .value {
      flex: 1;
      color: var(--color-text-2);
    }
    .ds-actions {
      position: absolute;
      right: 12px;
      bottom: 12px;
    }
  }
</style>
